package controller;

import modle.Bean.JDBCUtil;
import modle.Bean.User;
import modle.DAO.UserDao;
import org.json.JSONObject;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/UserEdit")
public class UserEditServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 5L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String real_name = request.getParameter("real_name");
        String tel = request.getParameter("tel");
        String username = request.getParameter("username");
        JDBCUtil db = new JDBCUtil();
        Connection conn = db.getConn();
        response.setContentType("text/javascript;charset=UTF-8");
        UserDao userDao = new UserDao();
        try {

                // 密码验证通过，更新数据库中用户密码
                userDao.updateUserInfo(conn,username,tel,real_name);
                // 将userList数据转换为json格式数据
                Map<String, Object> result = new HashMap<>();
                List<User> userList = userDao.getAllUsers(conn);  // 获取所有用户数据
                result.put("code", 0);
                result.put("msg", "请求成功");
                result.put("count", userList.size());
                result.put("data", userList);
                JSONObject json = new JSONObject(result);
                String jsonStr = json.toString();
                try (PrintWriter out = response.getWriter()) {
                    out.write(jsonStr);
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }

        } catch (Exception e) {

            throw new RuntimeException(e);
        }

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
